************
* PURPOSE:  Create Table 1
************

* Settings
version 16
do "$SSDIMed/scripts/_auxiliary/_project_settings.do"



*---------------------------------------------------------------------------------------------------------------------------------------
*** Table 1
*---------------------------------------------------------------------------------------------------------------------------------------

* Prepare for Table 1A

* Which controls were included in each regression
* y = incidence
*   local controls_01 none
*   local controls_02 i.fipscounty_init_g
* y = tot_pmt, died
*   local controls_01 i.years_since_covstart
*   local controls_02 i.years_since_covstart##i.fipscounty_init_g

*---------------------------------------------------------------------------------------------------------------------------------------
* Table 1, Panel A: All ages
*---------------------------------------------------------------------------------------------------------------------------------------

local panel_A_title "A. Cyclicality of DI entry and cohort outcomes (main sample)"

* Note: sample changed from main to 2262 on 2022-12-20
*local sample main
local sample 2262
tempfile table_1A
local replace replace

foreach y in incidence_pop_age_atapp tot_pmt died_adj {
  foreach ctrl in 02 {
    * Load estimates saved using regsave
    use "$SSDIMed/results/estimates/x-c.unemp_rate_county_atapp/x-c.unemp_rate_county_atapp_y-`y'_controls-`ctrl'_cluster-county_mofd_sample-`sample'.dta", clear
    capture confirm variable absvars
    local no_absvars = (_rc > 0)
    if strpos("`y'", "incidence") > 0       & `ctrl' == 01 assert cmd == "regress" & `no_absvars' == 1
    if strpos("`y'", "incidence") > 0       & `ctrl' == 02 assert cmd == "reghdfe" & absvars == "i.fipscounty_firstnm_g"
    if inlist("`y'", "tot_pmt", "died_adj") & `ctrl' == 01 assert cmd == "reghdfe" & absvars == "i.years_since_covstart"
    if inlist("`y'", "tot_pmt", "died_adj") & `ctrl' == 02 assert cmd == "reghdfe" & absvars == "i.years_since_covstart##i.fipscounty_firstnm_g"
    
    * Units
    * died in deaths per 10000
    foreach var in coef stderr y_mean_esample {
      if strpos("`y'", "died") > 0 replace `var' = `var'*10000
    }
    
    regsave_tbl using "`table_1A'", name(`y') asterisk(10 5 1) parentheses(stderr) format(%10.2fc) `replace'
    local replace append
  }
}

* Edit panel A
use `table_1A', clear
keep if inlist(var,"subtitle","unemp_rate_county_atapp_coef","unemp_rate_county_atapp_stderr","absvars","y_mean_esample","N") 

* additional rows
ingap 1
replace var = "panel_title" in 1 if mi(var)

gen dup = 2 if var == "absvars"
expand dup, gen(dupid)
replace var = "absvars2" if var == "absvars" & dupid == 1

label define var 1 "panel_title" 2 "unemp_rate_county_atapp_coef" 3 "unemp_rate_county_atapp_stderr" 4 "absvars" 5 "absvars2" 6 "y_mean_esample" 7 "N"
encode var, gen(num) label(var)
sort num 
drop num dup dupid

* Clean variable names
replace var = subinstr(var,"_coef","",1)
replace var = "" if strpos(var,"_stderr")
replace var = "Unemployment rate at application" 	  if var == "unemp_rate_county_atapp"
replace var = "Dependent variable mean" 				 	  if var == "y_mean_esample"
replace var = "Observations" 				 	              if var == "N"
replace var = "`panel_A_title'" 	                  if var == "panel_title"
replace incidence_pop_age_atapp = "County" 	        if var == "absvars"
replace incidence_pop_age_atapp = ""                if var == "absvars2"
replace tot_pmt   = "County \(\times\)" 	          if var == "absvars"
replace tot_pmt   = "Years enrolled"                if var == "absvars2"
replace died_adj      = "County \(\times\)" 	      if var == "absvars"
replace died_adj      = "Years enrolled"            if var == "absvars2"
replace var = "Fixed effects"                       if var == "absvars"  
replace var = "" 			                              if var == "absvars2" 

gen panel = "A"
save `table_1A', replace
list



* -----------------------------------------
* Table 1, Panel B: Ages 49 & 50 at entry
* -----------------------------------------
local panel_B_title "B. Cyclicality of DI entry and cohort outcomes, by age at entry (49--50)"

local sample 5152

tempfile table_1B
local replace replace

foreach y in incidence_pop_age_atapp tot_pmt died_adj {
  foreach ctrl in 02 {
    * Load estimates saved using regsave
    use "$SSDIMed/results/estimates/x-age52xUR/x-age52xUR_y-`y'_controls-`ctrl'_cluster-county_mofd_sample-`sample'", clear
    capture confirm variable absvars
    local no_absvars = (_rc > 0)
    if strpos("`y'", "incidence") > 0       & `ctrl' == 01 assert cmd == "regress" & `no_absvars' == 1
    if strpos("`y'", "incidence") > 0       & `ctrl' == 02 assert cmd == "reghdfe" & absvars == "i.fipscounty_firstnm_g"
    if inlist("`y'", "tot_pmt", "died_adj") & `ctrl' == 01 assert cmd == "reghdfe" & absvars == "i.years_since_covstart"
    if inlist("`y'", "tot_pmt", "died_adj") & `ctrl' == 02 assert cmd == "reghdfe" & absvars == "i.years_since_covstart##i.fipscounty_firstnm_g"
    
    * Units
    * died in deaths per 10000
    foreach var in coef stderr y_mean_esample {
      if strpos("`y'", "died") > 0 replace `var' = `var'*10000
    }
    
    regsave_tbl using "`table_1B'", name(`y') asterisk(10 5 1) parentheses(stderr) format(%10.2fc) `replace'
    local replace append
  }
}

* Edit Panel B
use `table_1B', clear
keep if strpos(var, "_coef") | strpos(var, "_stderr") | inlist(var,"subtitle","absvars","y_mean_esample","N") 

* additional rows
ingap 1
replace var = "panel_title" in 1 if mi(var)

gen dup = 2 if var == "absvars"
expand dup, gen(dupid)
replace var = "absvars2" if var == "absvars" & dupid == 1

label define var 1 "panel_title" 2 "_cons_coef" 3 "_cons_stderr" 4 "age52_coef" 5 "age52_stderr" 6 "UR_coef" 7 "UR_stderr" 8 "age52xUR_coef" 9 "age52xUR_stderr" 10 "absvars" 11 "absvars2" 12 "y_mean_esample" 13 "N"
encode var, gen(num) label(var)
sort num 
drop num dup dupid

* texsave will output these labels as column headers
label var col1 "Spec 3"
label var col2 "Spec 2"
label var col3 "Spec 1"

* Clean variable names
replace var = subinstr(var,"_coef","",1)
replace var = ""                                          if strpos(var,"_stderr")
replace var = "Intercept"  					                      if var=="_cons"
replace var = "Age 52 at entry"  					                if var=="age52"
replace var = "\textit{UR} (demeaned unemployment rate)"  if var=="UR"
replace var = "\textit{UR} \(\times\) Age 52 at entry"    if var=="age52xUR"
replace var = "Dependent variable mean" 				 	        if var == "y_mean_esample"
replace var = "Observations" 				 	                    if var == "N"
replace var = "`panel_B_title'" 	                        if var == "panel_title"
replace incidence_pop_age_atapp = "County" 	              if var == "absvars"
replace incidence_pop_age_atapp = ""                      if var == "absvars2"
replace tot_pmt   = "County \(\times\)" 	                if var == "absvars"
replace tot_pmt   = "Years enrolled"                      if var == "absvars2"
replace died_adj      = "County \(\times\)" 	            if var == "absvars"
replace died_adj      = "Years enrolled"                  if var == "absvars2"
replace var = "Fixed effects"                             if var == "absvars"  
replace var = "" 			                                    if var == "absvars2" 

gen panel = "B"
save `table_1B', replace
list


* Combine panels A and B
clear
append using `table_1A'
append using `table_1B'
list, sepby(panel)
drop panel

rename incidence_pop_age_atapp incidence

* texsave will output these labels as column headers
label var incidence "Entrants per million residents"
label var tot_pmt "Annual medical spending (\textdollar)"
label var died_adj "Annual mortality (deaths per 10,000)"

cap mkdir "$SSDIMed/results/tables"
local filename table1
local using using "$SSDIMed/results/tables/`filename'.tex"
local texsave_settings "replace autonumber nofix"
local marker marker("tab:`filename'")
local preamble preamble("\renewcommand\thetable{1}") 
local location location(h)
local size = "size(footnotesize)"
local title title(`"Cyclicality of DI entry, medical spending, and mortality"')
local fn footnote("Notes: Statistical significance at the 10, 5, and 1 percent levels indicated by *, **, and *** respectively.")
local hlines hlines(1 8)

* Export as LaTeX table
texsave `using', `texsave_settings' varlabels `marker' `hlines' `preamble' `location' `size' headlines("\setlength{\tabcolsep}{6pt}") `title' `fn'

* Additional LaTeX table tweaks
local texfile "$SSDIMed/results/tables/`filename'.tex"
text_replace "`texfile'" "`panel_A_title'&&&" "\BSaddlinespace[1.5ex]\BSmulticolumn{4}{l}{\BStextbf{`panel_A_title'}}"
text_replace "`texfile'" "`panel_B_title'&&&" "\BStabularnewline\BSmulticolumn{4}{l}{\BStextbf{`panel_B_title'}}"
text_replace "`texfile'" "Fixed effects" "\BSaddlinespace[1.5ex]Fixed effects"	
text_replace "`texfile'" "Dependent variable mean" "\BSaddlinespace[1.5ex]Dependent variable mean"	
text_replace "`texfile'" "documentclass{article}" "documentclass[12pt,letterpaper]{article}"

* Compile LaTeX table to PDF
pdflatex using "`texfile'", clean


** EOF
